package com.mezizy.ifaner.global;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.mezizy.ifaner.LogInActivity;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.Dish;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.Merchant;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.Order;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.OrderDish;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.StoreInf;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.User;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by Zizy on 15/2/2.
 */
public class Global {
    public static Context appContext;

    public static String userId;
    public static String userPwdSha;
    public static int userCredit;
    public static String userName;


    public static String moodleId;
    public static String moodlePwd;

    public static Map<String, Order> orderMap;


    public static String getJsonFromWebService(Map<String, String> data, String uri) throws Exception {

        Connection connection = Jsoup.connect(uri).data(data).timeout(5000);

        Document document = connection.get();

        String json = document.select("body").text();

        return json;

    }

    public static User getUserInf() {
        HashMap<String, String> map = getUserAuMap();
        String json = "";
        try {
            json = getJsonFromWebService(map, Config.IFANER_GET_USER_INF);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        List<User> user = (gson.fromJson(json, new TypeToken<List<User>>() {
        }.getType()));
        return user.get(0);

    }
    public static boolean sendGcmRegId(String gcmId) throws Exception {
        HashMap map=getUserAuMap();
        map.put("gcmId",gcmId);

        String json = getJsonFromWebService(map, Config.IFANER_REG_GCM_ID);
        return json.equals("true");

    }
    public static boolean addUser(String stuId, String stuPwd, String stuName) throws Exception {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerUserAccount", stuId);
        map.put("iFanerUserPassword", stuPwd);
        map.put("iFanerUserName", stuName);

        String json = getJsonFromWebService(map, Config.IFANER_ADD_USER_URI);

        if (json.equals("true")) {
            return true;
        } else {
            return false;

        }


    }

    public static Bitmap returnBitMap(String url) {
        //TODO 測試之後移除 網絡圖片地址
        url = "http://img5.imgtn.bdimg.com/it/u=2714863600,1578298657&fm=21&gp=0.jpg";

        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static String getStateS(int state) {
        switch (state) {
            case Config.STATE_CANCEL:
                return "已取消";
            case Config.STATE_CONFIRMED:
                return "訂單處理中";
            case Config.STATE_EXCEPTION:
                return "狀態異常";
            case Config.STATE_FINISHED_NOT_PAY:
                return "等待支付";
            case Config.STATE_FINISHED_PAID:
                return "已完成";
            case Config.STATE_NOT_CONFIRM:
                return "等待商家確認";


        }

        return "異常";
    }

    public static List<Dish> getDishesList(String merchantId) throws Exception {
        HashMap<String, String> map = getUserAuMap();
        map.put("merchantID", merchantId);

        String json = getJsonFromWebService(map, Config.IFANER_GET_DISH_LIST_URI);

        Gson gson = new Gson();
        List<Dish> list = gson.fromJson(json, new TypeToken<List<Dish>>() {
        }.getType());

        return list;
    }

    public static HashMap<String, String> getUserAuMap() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerUserAccount", Global.userId);
        map.put("iFanerUserPassword", Global.userPwdSha);
        return map;
    }

    public static List<Merchant> getMerchantList() throws Exception {
        HashMap<String, String> map = getUserAuMap();
//
//
//        map.put("iFanerUserAccount",  "test0");
//        map.put("iFanerUserPassword","00130362");


        String json = getJsonFromWebService(map, Config.IFANER_GET_MERCHANT_LIST_URI);

        Gson gson = new Gson();
        @SuppressWarnings("rawtypes")
        List<Merchant> list = gson.fromJson(json, new TypeToken<List<Merchant>>() {
        }.getType());
        return list;


    }

    public static String getDate() {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);

    }

    public static String encrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;


        byte[] bt = strSrc.getBytes();
        try {

            String encName = "SHA-256";

            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }


    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }


    static public Toast toast;


    public static void showToast(final String str, Activity activity) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(str);
            }
        });
    }

    public static void showToast(final String str, final int during, Activity activity) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(str, during);
            }
        });
    }

    public static void showToast(String str) {
        showToast(str, Toast.LENGTH_SHORT);
    }

    public static void showToast(String str, int during) {
        if (toast == null) {
            toast = Toast.makeText(Global.appContext, str, during);
        } else {
            toast.setText(str);

        }

        toast.show();
    }

    public static LinkedHashMap<String, Order> getOrderListUser() {
        try {
            String json = getJsonFromWebService(getUserAuMap(), Config.IFANER_GET_ORDER_LIST_USER);
            Gson gson = new Gson();
            LinkedList<OrderDish> list = gson.fromJson(json, new TypeToken<LinkedList<OrderDish>>() {
            }.getType());
            LinkedHashMap<String, Order> orderMap = new LinkedHashMap<>();
            List<Dish> dishList;


            for (Iterator<OrderDish> iterator = list.iterator(); iterator.hasNext(); ) {
                OrderDish orderDish = iterator.next();
                if (orderMap.get(orderDish.getTradeId()) == null) {//如果没有这个订单号码，加进去
                    dishList = new ArrayList<>();
                    dishList.add(new Dish(orderDish.getDishesId(), orderDish.getMerchantId(), orderDish.getAmount(), orderDish.getQuantity(), orderDish.getDishesName(), orderDish.getDishesPrice()));
                    orderMap.put(orderDish.getTradeId(), new Order(dishList, orderDish.getTradeId(), orderDish.getCusId(), orderDish.getMerchantId(), orderDish.getTradeState(), orderDish.getAmount(), orderDish.getCreateTime(), orderDish.getRemarks(), orderDish.getDeliverPlace(), orderDish.getMerchantName()));

                } else {//如果存在了这个订单号码
                    dishList = orderMap.get(orderDish.getTradeId()).getDishList();
                    dishList.add(new Dish(orderDish.getDishesId(), orderDish.getMerchantId(), orderDish.getAmount(), orderDish.getQuantity(), orderDish.getDishesName(), orderDish.getDishesPrice()));
                    orderMap.get(orderDish.getTradeId()).setDishList(dishList);
                }
                orderMap.get(orderDish.getTradeId()).setAmount(getOrderTotalPrice(dishList));

            }
            Global.orderMap = orderMap;
            return orderMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final int BLACK = 0xff000000;

    /**
     * 生成一个二维码图像
     *
     * @param str            传入的字符串，通常是一个URL
     * @param widthAndHeight 图像的宽高
     * @return
     */
    public static Bitmap createQRCode(String str, int widthAndHeight)
            throws WriterException {
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix matrix = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
        matrix=deleteWhite(matrix);

        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = BLACK;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
    public static BitMatrix deleteWhite(BitMatrix matrix){
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    public static float getOrderTotalPrice(List<Dish> dishList) {
        float total = 0;
        for (Dish dish : dishList) {
            total += dish.getTotal();
        }
        return total;
    }

    public static String getFreeId() {
        HashMap<String, String> map = getUserAuMap();
        String json = null;
        try {
            json = getJsonFromWebService(map, Config.IFANER_GET_FREE_ID__URI);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public static StoreInf getStoreInf(String merchantId) {
        HashMap<String, String> map = getUserAuMap();
        map.put("merchantID", merchantId);
        String json = "";
        try {
            json = getJsonFromWebService(map, Config.IFANER_GET_STORE_INF_URI);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        List<StoreInf> storeInf = null;
        try{
         storeInf= gson.fromJson(json, new TypeToken<List<StoreInf>>() {
        }.getType());
        }catch (Exception e){
            e.printStackTrace();
        }
        if (storeInf == null) {
            return null;
        }
        else{
            return storeInf.get(0);

        }
    }

    public static void activityLogInCheck(Activity activity) {
        if (Global.userId == null || Global.userPwdSha == null) {
            activity.startActivity(new Intent(activity, LogInActivity.class));
            activity.finish();
        }
    }

    public static ProgressDialog mProgressDialog;

    public static void showProgress(final Activity context, final String msg) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                }
                mProgressDialog = new ProgressDialog(context);

                mProgressDialog.setTitle("提示");
                mProgressDialog.setMessage(msg);
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }
        });

    }

    public static void dismissProgress(final Activity context) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                }
            }
        });

    }


    public static boolean postOrder(String orderId, String merchantId, List<Dish> listDish, String remark, String deliverPlace) {
        //TODO 发送订单
        HashMap<String, String> map = getUserAuMap();

        for (Iterator<Dish> iterator = listDish.iterator(); iterator.hasNext(); ) {
            Dish dish = iterator.next();
            if (dish.getCartQuantity() == 0) {
                continue;
            }

            map.put("orderID", orderId);
//            map.put("orderDate", getDate());
            map.put("merchantId", merchantId);
            map.put("dishesID", dish.getDishesId());
            map.put("quantity", "" + dish.getCartQuantity());
            map.put("remarks", ChangeCode.toLong(remark));
            map.put("deliverPlace", ChangeCode.toLong(deliverPlace));

            try {
                getJsonFromWebService(map, Config.IFANER_POST_ORDER_URI);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

        }
        return true;
    }


    public static boolean moodleAuthorize(String stuId, String password) {
        /* 建立HTTP POST連線 */
        HttpPost httpRequest = new HttpPost(Config.MOODLE_LOG_IN_URI);

		/* POST運作傳送變數必須用NameValuePair[]陣列儲存 */

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id", stuId));
        params.add(new BasicNameValuePair("password", password));
        params.add(new BasicNameValuePair("ip", "120.96.99.54"));
        params.add(new BasicNameValuePair("idtype", "s"));
        params.add(new BasicNameValuePair("type", "1"));

        try {

			/* 發出HTTP Request */
            httpRequest.setEntity(new UrlEncodedFormEntity(params, "big5"));

			/* 取得HTTP Response */
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

			/* 若狀態碼為200則OK */
            if (httpResponse.getStatusLine().getStatusCode() == 200) {

				/* 取出回應字串 */
                String strResult = EntityUtils.toString(httpResponse.getEntity());

				/* 檢驗帳號密碼是否正確 (用mobilepassword的值檢測：0為正確, 1為錯誤) */
                int index = strResult.indexOf("mobilepassword");
                int LoginCheck = Integer.parseInt(strResult.substring(index + 17, index + 18));
                if (LoginCheck == 0) {
                    return Config.MOODLE_LOG_IN_SUCCESS;
                } else {
                    return Config.MOODLE_LOG_IN_FAILED;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Config.MOODLE_LOG_IN_FAILED;
    }


    public static int userAuthorize(String stuId, String stuPwdSha) {
//
//        HttpPost httpRequest = new HttpPost(Config.IFANER_LOG_IN_URI);
//
//
//        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        params.add(new BasicNameValuePair("iFanerUserAccount", userId));
//        params.add(new BasicNameValuePair("iFanerUserPassword", userPwdSha));


//        Map<String, String> map = getUserAuMap();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerUserAccount", stuId);
        map.put("iFanerUserPassword", stuPwdSha);

        try {
            String result = getJsonFromWebService(map, Config.IFANER_LOG_IN_URI);
            if (result.equals("true")) {
                return Config.IFANER_LOG_IN_SUCCESS;
            } else {
                return Config.IFANER_LOG_IN_FAILED_AU;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return Config.IFANER_LOG_IN_FAILED_INTERNET;

        }
//        try {

//            httpRequest.setEntity(new UrlEncodedFormEntity(params, "big5"));
//
//            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
//
//            if (httpResponse.getStatusLine().getStatusCode() == 200) {
//
//                String strResult = EntityUtils.toString(httpResponse.getEntity());
//
//                int index = strResult.indexOf("true");
//
//                if (index != -1) {
//                    return Config.IFANER_LOG_IN_SUCCESS;
//
//                } else if (strResult.indexOf("false") != -1) {
//                    return Config.IFANER_LOG_IN_FAILED_AU;
//                }
//            }
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//            return Config.IFANER_LOG_IN_FAILED_INTERNET;
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Config.IFANER_LOG_IN_FAILED_INTERNET;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Config.IFANER_LOG_IN_FAILED_INTERNET;
//        }
//        return Config.IFANER_LOG_IN_FAILED_INTERNET;
    }


}


